package com.zxbit.flash.ui.activity;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.google.gson.Gson;
import com.zxbit.flash.R;
import com.zxbit.flash.base.BaseTitleActivity;
import com.zxbit.flash.common.Constant;
import com.zxbit.flash.common.RouterMap;
import com.zxbit.flash.bean.JsOrderData;
import com.zxbit.flash.utils.DebugLog;
import com.zxbit.flash.utils.StringUtils;
import com.zxbit.flash.utils.ToastUtils;

import butterknife.BindView;
import butterknife.ButterKnife;

@Route(name = "webview页面", path = RouterMap.WEB_VIEW_PAGE)
public class WebViewActivity extends BaseTitleActivity {

    @BindView(R.id.webview)
    WebView webview;

    @Autowired(name = Constant.PARAMS_URL)
    String mUrl;
    @Autowired(name = Constant.PARAMS_TYPE)
    int mType;
    @Autowired(name = Constant.PARAMS_ORDER_DATA)
    JsOrderData orderData;
    private String TAG = WebViewActivity.class.getSimpleName();

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        initWebSetting();

        // 1 关于我们  2借款协议  3还款指南  4注册协议
        switch (mType){
            case Constant.WEB_TYPE_ABOUT:
                setTitleText(getStringResource(R.string.web_title_about_us));
                break;
            case Constant.WEB_TYPE_LOAN:
                setTitleText(getStringResource(R.string.web_title_loan_policy));
                break;
            case Constant.WEB_TYPE_GUIDE:
                setTitleText(getStringResource(R.string.web_title_repayment_guide));
                break;
            case Constant.WEB_TYPE_REGISTER:
                setTitleText(getStringResource(R.string.web_title_register_policy));
                break;
            default:
                break;
        }
    }

    @Override
    protected void onUIReady() {
        if (StringUtils.isEmpty(mUrl)) {
            ToastUtils.showShort(WebViewActivity.this, getStringResource(R.string.incorrect_parameters));
            finish();
        }
        if (mType == Constant.WEB_TYPE_LOAN && orderData == null) {
            ToastUtils.showShort(WebViewActivity.this, getStringResource(R.string.incorrect_parameters));
        }

        webview.loadUrl(mUrl);
    }



    @SuppressLint("SetJavaScriptEnabled")
    private void initWebSetting() {
        webview.addJavascriptInterface(new JavaScript(), "jsi");
        webview.setWebChromeClient(new WebChromeClient() {

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                //对alert的简单封装
                new AlertDialog.Builder(WebViewActivity.this).
                        setTitle("Alert").setMessage(message).setPositiveButton("OK",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface arg0, int arg1) {}
                        }).create().show();

                return super.onJsAlert(view, url, message, result);
            }
        });
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return true;
            }
        });
        webview.getSettings().setJavaScriptEnabled(true);
        webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    }

    @Override
    protected int getContentResId() {
        return R.layout.activity_webview;
    }

    @Override
    public String getPageTitle() {
        return "";
    }

    private final class JavaScript {
        @JavascriptInterface
        public void getOrderInfoData() {
            WebViewActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (webview != null && orderData != null) {
                        // Android版本变量
                        final int version = Build.VERSION.SDK_INT;

                        StringBuilder builder = new StringBuilder();
                        builder.append("javascript:call_back_getOrderInfoData(");
                        builder.append(new Gson().toJson(orderData));
                        builder.append(")");

                        if (version < 18) {
                            webview.loadUrl(builder.toString());
                        } else {
                            webview.evaluateJavascript(builder.toString(), new ValueCallback<String>() {
                                @Override
                                public void onReceiveValue(String value) {

                                }
                            });
                        }
                    }
                }
            });
        }

        @JavascriptInterface
        public void displayTraceStatus(String status) {
            if (StringUtils.isEmpty(status)) return;
            if (!String.valueOf(Constant.HTTP_OK).equalsIgnoreCase(status)) {
                DebugLog.e(TAG, "webview geted status:" + status);
                if (String.valueOf(Constant.LOGIN_TIMEOUT).equalsIgnoreCase(status)) {
                    ARouter.getInstance().build(RouterMap.MAIN_ACTIVITY_PAGE).navigation();
                }
            }

        }
    }

}
